<template>
    <view class="container">
        <view style="margin-top: 370rpx;" class="login-from">
            <label class="loginLab">使用教务系统账号密码直接登录</label>
            <!--账号-->
            <view style="margin-top: 20px;" class="inputView">
                <label class="loginLab">账号</label>
                <input class="inputText" placeholder="请输入账号" :value="username" @input="usernameInput"/>
            </view>
            <view class="line"></view>
            <!--密码-->
            <view style="margin-top: 20px;" class="inputView">
                <label class="loginLab">密码</label>
                <input class="inputText" :password="true" placeholder="请输入密码" @input="pwdInput"/>
            </view>

            <!--按钮-->
            <view class="loginBtnView">
                <button class="loginBtn" type="primary" :disabled="!logining" @tap="loginFun">登录</button>
            </view>

            <view class="cu-modal bottom-modal" :class="modalShow ?'show':''" @tap="cancel">
                <view class="cu-dialog" @tap.stop="">
                    <view class="cu-bar bg-white">
                        <view class="action text-red" @tap="cancel">取消</view>
                        <view class="action text-blue" @tap="sure">确定</view>
                    </view>
                    <view class="grid col-3 padding-sm">
                        <view v-for="(item,index) in schoolList" class="padding-xs" :key="index">
                            <button class="cu-btn blue lg block" :class="item.checked?'bg-blue':'line-blue'" @tap="ChooseSchool" :data-value="item.value">
                                {{item.name}}
                            </button>
                        </view>
                    </view>
                </view>
            </view>

        </view>
    </view>
</template>

<script>
const app = getApp();

const getData = (url, param) => {
    return new Promise((resolve, reject) => {
        uni.request({
            url: url,
            method: 'POST',
            data: param,
            header: {
                'Content-Type': 'application/json'
            },

            success(res) {
                resolve(res.data);
            },

            fail(err) {
                reject(err);
            }
        });
    });
};

export default {
    data() {
        return {
            username: '',
            password: '',
            logining: true,

            modalShow: false,
            schoolId: -1,
            schoolList: []
        };
    }
    /**
     * 生命周期函数--监听页面加载
     */,
    onLoad: function (options) {

        let that = this;

        let userName;

        if (uni.getStorageSync('username')) {
            userName = uni.getStorageSync('username');
            that.setData({
                username: userName
            })
        }

        that.getSchoolList();


    },
    onBackPress(option) {
        return true;
    },
    onPullDownRefresh() {
        uni.stopPullDownRefresh();
    },
    methods: {
        usernameInput: function (e) {
            this.setData({
                username: e.detail.value
            });
        },

        pwdInput: function (e) {
            this.setData({
                password: e.detail.value
            });
        },
        loginFun: function () {

            let that = this;

            that.setData({
                logining: false
            })

            uni.showLoading({
                title: "正在登陆中..."
            });
            getData(app.globalData.ApiUrl + 'api/Android/Login', {
                username: that.username,
                pwd: that.password
            }).then((msg) => {

                uni.hideLoading();

                if (msg.result === 'success') {

                    //如果没有数据，则选择学校
                    if (msg.type && msg.type == 2){

                        that.setData({
                            modalShow: true
                        });

                        return;
                    }


                    uni.setStorageSync('SafeCode', msg.SafeCode);
                    uni.setStorageSync('username', that.username);
                    uni.showModal({
                        title: '操作结果',
                        content: msg.msg,
                        success() {
                            // 后台请求更新课程表
                            if (msg.type && msg.type == 1) {
                                getData(app.globalData.ApiUrl + 'api/Android/updateTable', {
                                    SafeCode: msg.SafeCode
                                }).then((msg) => {

                                    console.log(msg);
                                    if (msg.result === 'success') {
                                        uni.showToast({
                                            title: '课程表更新成功',
                                            duration: 2000
                                        });
                                    } else {
                                        uni.showToast({
                                            title: '课程表更新失败',
                                            icon: 'error',
                                            duration: 2000
                                        });
                                    }
                                })
                            }
							
							uni.reLaunch({
								url:"/pages/home/home"
							})
							
							// uni.switchTab({
							// 	url: '../../pages/home/home'
							// });
							// uni.navigateBack({
							// 	delta:1
							// });
                            // uni.navigateTo({
                            //     url: "/home/home"
                            // })
                        }
                    });
                } else {

                    that.setData({
                        logining: true
                    })

                    uni.showModal({
                        title: '错误',
                        content: msg.msg
                    });
                }
            });
        },

        /**
         * 选择学校
         * @param e
         * @constructor
         */
        ChooseSchool(e) {
            let that = this;
            let value = e.currentTarget.dataset.value;

            //先全部取消
            for (let i = 0, lenI = that.schoolList.length; i < lenI; ++i) {

                that.schoolList[i].checked = false;

            }

            //再选择
            for (let i = 0, lenI = that.schoolList.length; i < lenI; ++i) {

                if (that.schoolList[i].value === value) {
                    that.schoolList[i].checked = !that.schoolList[i].checked;
                    that.setData({
                        schoolId: that.schoolList[i].value
                    })
                    break;
                }
            }
        },

        cancel: function () {
            this.setData({
                modalShow: false,
                logining: true
            });
            console.log('取消');

        },
        sure: function () {

            uni.showLoading("正在登陆中...");

            const that = this;

            if(this.schoolId === -1){
                uni.showModal({
                    title: '错误',
                    content: '请选择一个学校！'
                });
                return;
            }

            getData(app.globalData.ApiUrl + 'api/Android/registerAndLogin', {
                username: that.username,
                pwd: that.password,
                schoolId: that.schoolId
            }).then((msg) => {

                console.log(msg);

                if (msg.result === 'success') {
                    uni.setStorageSync('SafeCode', msg.SafeCode);
                    uni.setStorageSync('username', that.username);
                    uni.showModal({
                        title: '操作结果',
                        content: msg.msg,
                        success() {
                            // 后台请求更新课程表
                            if (msg.type && msg.type === 1) {
                                getData(app.globalData.ApiUrl + 'api/Android/updateTable', {
                                    SafeCode: msg.SafeCode
                                }).then((msg) => {

                                    console.log(msg);
                                    if (msg.result === 'success') {
                                        uni.showToast({
                                            title: '课程表更新成功',
                                            duration: 2000
                                        });
                                    } else {
                                        uni.showToast({
                                            title: '课程表更新失败',
                                            icon: 'error',
                                            duration: 2000
                                        });
                                    }
                                })
                            }
                            uni.navigateTo({
                                url: "../home/home"
                            })
                        }
                    });
                }else{
                    uni.showModal({
                        title: '登录失败',
                        content: msg.msg,
                    });
                    this.setData({
                        logining: true
                    });
                }

                uni.hideLoading();

            })
            this.setData({
                modalShow: false
            })
            console.log('确定'+this.schoolId);
        },
        /**
         * 更新课程表
         */
        updateTable: function (SafeCode) {

            console.log('更新课程表');


        },
        /**
         * 获取学校列表
         */
        getSchoolList: function () {
            const that = this;
            getData(app.globalData.ApiUrl + 'api/Android/getSchoolList').then((msg) => {

                console.log(msg);
                that.schoolList = msg.data;
            });
        }
    }
};
</script>
<style>
@import './bind.css';
</style>
